package org.algorithm.Backtracking.leetcode47;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {

        Arrays.sort(nums);
        boolean [] used = new boolean[nums.length];
        Arrays.fill(used,false);
        backtracking(nums,used);
        return res;
    }

    private void backtracking(int []nums,boolean [] used){
        if (item.size()==nums.length){
            res.add(new ArrayList<>(item));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i>0 && nums[i]==nums[i-1] && !used[i-1]){
                continue;
            }
            if (!used[i]){
                used[i]=true;
                item.add(nums[i]);
                backtracking(nums,used);
                used[i]=false;
                item.remove(item.size()-1);
            }
        }

    }

}
